"""
FastAPI服务 - 用于PyQt应用与浏览器插件通信
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
from typing import Optional
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="快手商品排行榜API服务")

# 配置CORS，允许浏览器插件访问
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，因为浏览器插件需要访问
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 用于存储最新的搜索请求
latest_search_request: dict[str, Optional[str | float]] = {
    "text": None,
    "timestamp": None
}


class SearchRequest(BaseModel):
    """搜索请求模型"""
    search_text: str
    source: Optional[str] = "pyqt_app"


class SearchResponse(BaseModel):
    """搜索响应模型"""
    status: str
    message: str
    search_text: Optional[str] = None


@app.get("/")
async def root():
    """根路径"""
    return {"message": "快手商品排行榜API服务运行中"}


@app.post("/api/search", response_model=SearchResponse)
async def trigger_search(request: SearchRequest):
    """
    接收来自PyQt应用的搜索请求
    浏览器插件会轮询 /api/get_search 来获取最新的搜索文本
    """
    global latest_search_request
    import time
    
    latest_search_request["text"] = request.search_text
    latest_search_request["timestamp"] = time.time()
    
    logger.info(f"收到搜索请求: {request.search_text}")
    
    return SearchResponse(
        status="success",
        message="搜索请求已接收",
        search_text=request.search_text
    )


@app.get("/api/get_search")
async def get_latest_search():
    """
    供浏览器插件轮询获取最新的搜索请求
    """
    global latest_search_request
    import time
    
    # 如果有搜索请求且不超过5秒，返回它
    if latest_search_request["text"] is not None and latest_search_request["timestamp"] is not None:
        current_time = time.time()
        # 确保 timestamp 是数字类型再进行计算
        timestamp = latest_search_request["timestamp"]
        if isinstance(timestamp, (int, float)) and current_time - timestamp < 5:
            search_text = latest_search_request["text"]
            # 清空已返回的搜索请求
            latest_search_request["text"] = None
            latest_search_request["timestamp"] = None
            
            logger.info(f"返回搜索文本: {search_text}")
            return {"search_text": search_text, "has_request": True}
    
    return {"search_text": None, "has_request": False}


@app.get("/api/health")
async def health_check():
    """健康检查"""
    return {"status": "ok", "service": "快手商品排行榜API服务"}


def start_api_server(host="127.0.0.1", port=8765):
    """启动API服务器（兼容在线程中运行，禁用信号处理）"""
    # 尝试获取全局的GUI窗口实例并重定向日志
    try:
        import sys
        for obj in globals().values():
            if hasattr(obj, 'add_log_message'):
                obj.add_log_message(f"✅ 启动API服务器: http://{host}:{port}", "#4ade80")
                break
    except Exception:
        pass

    logger.info(f"启动API服务器: http://{host}:{port}")

    # 配置uvicorn日志处理器，将日志重定向到GUI
    class UvicornLogHandler(logging.Handler):
        def emit(self, record):
            try:
                import sys
                for obj in globals().values():
                    if hasattr(obj, 'add_log_message'):
                        color = "#94a3b8"
                        if record.levelno >= logging.ERROR:
                            color = "#f87171"
                        elif record.levelno >= logging.WARNING:
                            color = "#fbbf24"
                        elif record.levelno >= logging.INFO:
                            color = "#4ade80"
                        obj.add_log_message(self.format(record), color)
                        break
            except Exception:
                pass

    try:
        # 以“无信号处理”的方式运行 uvicorn，避免在子线程中崩溃
        from uvicorn import Config, Server
        # 关闭 uvicorn 默认日志配置，避免 "formatter 'default'" 错误；关闭 access_log 降低噪音
        config = Config(app, host=host, port=port, log_level="info", log_config=None, access_log=False)
        server = Server(config)
        # 禁用信号处理（在子线程中必须）
        if hasattr(server, "install_signal_handlers"):
            server.install_signal_handlers = lambda: None
        # 将 uvicorn 日志输出到 GUI
        logging.getLogger("uvicorn").addHandler(UvicornLogHandler())
        server.run()
    except Exception as e:
        logger.exception(f"API服务器启动失败: {e}")
        try:
            for obj in globals().values():
                if hasattr(obj, 'add_log_message'):
                    obj.add_log_message(f"⚠️ API服务器启动失败: {e}", "#f87171")
                    break
        except Exception:
            pass


# 添加全局变量用于存储GUI窗口实例
gui_window_instance = None


def set_gui_window_instance(window):
    """设置GUI窗口实例，用于日志重定向"""
    global gui_window_instance
    gui_window_instance = window


if __name__ == "__main__":
    start_api_server()